package com.cssw.fyzb.tps.service.res.adapter;

import com.cssw.fyzb.tps.config.res.CosConfiguration;
import com.cssw.fyzb.tps.config.res.OssConfiguration;
import com.cssw.fyzb.tps.config.res.ResConfiguration;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Feng Chen
 */
@SuppressWarnings("unchecked")
public class ResAdapterFactory {

    private final static Map<Class<? extends ResConfiguration>, ResAdapterCreator> CREATOR_MAP
            = new HashMap<Class<? extends ResConfiguration>, ResAdapterCreator>();

    static {
        CREATOR_MAP.put(OssConfiguration.class, new OssAdapterCreator());
        CREATOR_MAP.put(CosConfiguration.class, new CosAdapterCreator());
    }

    public static ResAdapter createResAdapter(ResConfiguration configuration) {
        Class resConfigType;
        boolean isCompatibleType;
        Iterator it = CREATOR_MAP.keySet().iterator();
        do {
            if (!it.hasNext()) {
                throw new IllegalArgumentException("Unrecognized configuration type: " + configuration.getClass());
            }

            resConfigType = (Class) it.next();
            isCompatibleType = resConfigType.isAssignableFrom(configuration.getClass());
        } while (!isCompatibleType);

        return CREATOR_MAP.get(configuration.getClass()).create(configuration);
    }

    private static class OssAdapterCreator implements ResAdapterCreator<OssConfiguration> {

        @Override
        public ResAdapter create(OssConfiguration configuration) {
            return new OssAdapter(configuration);
        }
    }

    private static class CosAdapterCreator implements ResAdapterCreator<CosConfiguration> {

        @Override
        public ResAdapter create(CosConfiguration configuration) {
            return new CosAdapter(configuration);
        }
    }

    private static interface ResAdapterCreator<T extends ResConfiguration> {
        ResAdapter create(T configuration);
    }


}
